package datalookin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.util.ArrayList;
import java.util.List;

import datalookin.adapter.ChoosePlantAdapter;
import datalookin.adapter.MonitorAdapter;
import datalookin.dto.StationAllDataDto;
import datalookin.network.AllStationcodeByplantCode;
import datalookin.network.GetRealStationDataAction;
import inter.Delegate;
import model.WaterPlant;
import utils.CacheHelper;

/**
 * 管网实时监测数据
 * Created by Administrator on 2016/3/4.
 */
public class GuanWangMonitorActivity extends UIHandler.BaseActivity {


    Button btn_back;
    View v_real;
    View v_history;

    ListView lv_monitor;
    MonitorAdapter monitorAdapter;
    List<StationAllDataDto> stationAllDataDtos = new ArrayList<StationAllDataDto>();

    SwipeRefreshLayout swipeRefreshLayout;

//    GetAllRealWaterInfo getAllRealWaterInfo;

    Spinner spinner_plant;

    private List<WaterPlant> waterPlants = new ArrayList<WaterPlant>();
    ChoosePlantAdapter choosePlantAdapter = new ChoosePlantAdapter();
    {
        choosePlantAdapter.setPlants(waterPlants);
    }

    // 获取所有的实时站点信息
    GetRealStationDataAction getRealStationDataAction;

    // 获取水厂的站点信息
    AllStationcodeByplantCode stationcodeByplantCode;


    /**
     * 动作
     */
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_back) {
                GuanWangMonitorActivity.this.finish();
            } else if (v == v_real) {

            } else if (v == v_history) {
                Intent intent = new Intent(GuanWangMonitorActivity.this, GuanWangHistoryActivity.class);
                GuanWangMonitorActivity.this.startActivity(intent);
            }
        }
    };

    /**
     * 实时数据响应
     */
    Delegate realDataImp = new Delegate() {
        @Override
        public void onResponse(String response) {

            if (swipeRefreshLayout.isRefreshing())
                swipeRefreshLayout.setRefreshing(false);
            if (!response.startsWith("["))
            {
                stationAllDataDtos.clear();
                monitorAdapter.notifyDataSetChanged();
                return;
            }
            List<StationAllDataDto> dataDtos =  JSON.parseArray(response, StationAllDataDto.class);
            stationAllDataDtos.clear();
            stationAllDataDtos.addAll(dataDtos);
            monitorAdapter.notifyDataSetChanged();

            // 保存站点信息

//            MyApplication.aCache.put(CacheHelper.PLANTSTATIONS,response);
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            swipeRefreshLayout.setRefreshing(false);
            Toast.makeText(GuanWangMonitorActivity.this, "实时数据获取失败", Toast.LENGTH_SHORT).show();
        }
    };

     // 水厂的站点信息
    Delegate stationsinPlant = new Delegate() {
        @Override
        public void onResponse(String response) {
            swipeRefreshLayout.setRefreshing(false);
            if (!response.startsWith("["))
                return;

            CacheHelper preferenceHelper = new CacheHelper(GuanWangMonitorActivity.this);
            preferenceHelper.putString(CacheHelper.PLANTSTATIONS, "data", response);
            List<WaterPlant> waterPlantsTmp = JSON.parseArray(
                    response, WaterPlant.class);
            waterPlants.clear();
            waterPlants.addAll(waterPlantsTmp);
            choosePlantAdapter.notifyDataSetChanged();

        }

        @Override
        public void onErrorResponse(VolleyError error) {
            swipeRefreshLayout.setRefreshing(false);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor);
        initview();
        initdata();
    }

    // 初始化界面
    private void initdata() {
        CacheHelper preferenceHelper = new CacheHelper(GuanWangMonitorActivity.this);
        if (preferenceHelper.contains(CacheHelper.ALLWATERPLANT,"data"))
        {
            List<WaterPlant> waterPlantsTmp = JSON.parseArray(
                    preferenceHelper.getString(CacheHelper.ALLWATERPLANT, "data"), WaterPlant.class);
            waterPlants.addAll(waterPlantsTmp);
            choosePlantAdapter.notifyDataSetChanged();
        }

    }

    private void initview() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(onClickListener);
        v_real = findViewById(R.id.id_bottom_real);
        v_real.setOnClickListener(onClickListener);
        v_history = findViewById(R.id.id_bottom_history);
        v_history.setOnClickListener(onClickListener);
        lv_monitor = (ListView) findViewById(R.id.id_lv_historyplant);
        lv_monitor.setEmptyView(findViewById(R.id.id_v_nonemsg));
        monitorAdapter = new MonitorAdapter();
        monitorAdapter.setStationAllDataDtos(stationAllDataDtos);
        lv_monitor.setAdapter(monitorAdapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.id_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                askRealData();
            }
        });

        spinner_plant = (Spinner) findViewById(R.id.id_spinner_plant);
        spinner_plant.setAdapter(choosePlantAdapter);
        spinner_plant.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                WaterPlant waterPlant = (WaterPlant) view.getTag();
                onchoosePlant(waterPlant);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        askRealData();

    }

    // 选择水厂
    private void onchoosePlant(WaterPlant waterPlant) {
        getRealStationDataAction = new GetRealStationDataAction(realDataImp,waterPlant.getWaterPlantCode());
        getRealStationDataAction.get();

//        // 获取水厂的站点信息
//        stationcodeByplantCode = new AllStationcodeByplantCode();
//        stationcodeByplantCode.setDelegate(stationsinPlant);
//        stationcodeByplantCode.setWaterPlantCode(waterPlant.getWaterPlantCode());
//        stationcodeByplantCode.get();


    }

    /**
     * 请求刷新实时数据
     */
    public void askRealData() {
        if (getRealStationDataAction != null)
            getRealStationDataAction.get();
        else
            swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (getAllRealWaterInfo != null)
//            getAllRealWaterInfo.cancel();
        if (getRealStationDataAction != null)
            getRealStationDataAction.cancel();

//        if (stationcodeByplantCode != null)
//            stationcodeByplantCode.cancel();
    }
}
